<template>
  <div v-if="popupVisible" class="custom-popup" :style="popupStyle">
    <div class="popup-content">
      <p><strong>编号：</strong>{{ popupData.id || "无" }}</p>
      <p><strong>类型：</strong>{{ popupData.type || "无" }}</p>
      <p><strong>经度：</strong>{{ popupData.lng.toFixed(6) }}</p>
      <p><strong>纬度：</strong>{{ popupData.lat.toFixed(6) }}</p>
      <div class="btn">
        <button @click="btnClick">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, nextTick } from "vue"
import { showMessage } from "../utils/messageUtils"
const { proxy } = getCurrentInstance()
import { useMineStore } from "@/stores/mineMap"
import { addHighlightLayer, removeHighlightLayer } from "@/utils/HighLayer"
// 加载点数据
import jsonData from "../assets/point.json"

// 导入图标资源
import ballIcon from "../assets/ball.png"
import gunIcon from "../assets/gun.png"
import { storeToRefs } from "pinia"

// 导入 Draw.js 中的方法
import { drawCircle, drawSector, removeLayer } from "@/utils/Draw"

// 弹窗相关状态
const popupData = ref({ id: null, type: null, lng: null, lat: null })
const popupStyle = ref({ top: "0px", left: "0px" })
const { popupVisible, clickedFeatureCoordinates } = storeToRefs(useMineStore())
// 关闭弹窗
const { closePopup } = useMineStore()

// 存储当前绘制的图层 ID
const currentLayerId = ref(null)

// 关闭弹窗以及高亮图层
const btnClick = () => {
  // 关闭弹窗
  closePopup()
  // 移除高亮图层
  removeHighlightLayer(proxy.$map)
  // 移除当前绘制的图形图层
  if (currentLayerId.value) {
    removeLayer(proxy.$map, currentLayerId.value)
    currentLayerId.value = null // 重置当前图层 ID
  }
}

onMounted(() => {
  const map = proxy.$map

  map.on("load", function () {
    if (map && map.isStyleLoaded()) {
      showMessage("地图资源加载完成！", "success")

      // 加载图标
      map.loadImage(ballIcon, function (error, image) {
        if (error) throw error
        map.addImage("Ball", image)

        map.loadImage(gunIcon, function (error, image) {
          if (error) throw error
          map.addImage("Gun", image)

          // 添加数据源
          map.addSource("pointSource", {
            type: "geojson",
            data: jsonData,
          })

          // 添加图层
          map.addLayer({
            id: "symbolLayer",
            type: "symbol",
            source: "pointSource",
            layout: {
              "icon-image": "{kind}",
              "icon-size": 3.0,
              "icon-allow-overlap": true,
              visibility: "visible",
            },
            minzoom: 7,
            maxzoom: 17.5,
          })

          // 监听点击事件
          map.on("click", "symbolLayer", (e) => {
            const features = map.queryRenderedFeatures(e.point, {
              layers: ["symbolLayer"],
            })

            if (features.length > 0) {
              const feature = features[0]
              const properties = feature.properties
              clickedFeatureCoordinates.value = feature.geometry.coordinates

              // 更新弹窗数据
              popupData.value = {
                id: properties.id || "无",
                type: properties.title || "无",
                lng: clickedFeatureCoordinates.value[0],
                lat: clickedFeatureCoordinates.value[1],
              }

              // 显示弹窗
              popupVisible.value = true

              // 确保 DOM 更新后再计算位置
              nextTick(() => {
                updatePopupPosition(map, clickedFeatureCoordinates.value)
              })

              // 添加高亮图层
              addHighlightLayer(map, feature)

              // 移除之前的图形图层
              if (currentLayerId.value) {
                removeLayer(map, currentLayerId.value)
              }

              // 根据 kind 类型绘制图形
              if (properties.kind === "Ball") {
                drawCircle(
                  map,
                  clickedFeatureCoordinates.value,
                  4000,
                  "circle-layer",
                  "#FF0000",
                  0.5
                )
                currentLayerId.value = "circle-layer" // 更新当前图层 ID
              } else if (properties.kind === "Gun") {
                drawSector(
                  map,
                  clickedFeatureCoordinates.value,
                  4000,
                  45,
                  135,
                  "sector-layer",
                  "#00FF00",
                  0.5
                )
                currentLayerId.value = "sector-layer" // 更新当前图层 ID
              }
            }

            // 飞行效果
            map.flyTo({
              center: [
                clickedFeatureCoordinates.value[0],
                clickedFeatureCoordinates.value[1],
              ],
              zoom: 12,
              bearing: 10,
              pitch: 30,
              duration: 2000,
            })
          })

          // 监听地图拖动事件
          map.on("move", () => {
            if (clickedFeatureCoordinates.value) {
              updatePopupPosition(map, clickedFeatureCoordinates.value)
            }
          })
        })
      })
    }
  })
})

// 更新弹窗位置
const updatePopupPosition = (map, coordinates) => {
  const point = map.project(coordinates)
  const popupElement = document.querySelector(".custom-popup")
  if (popupElement) {
    const popupWidth = popupElement.offsetWidth
    const popupHeight = popupElement.offsetHeight
    const offsetY = 20

    popupStyle.value = {
      top: `${point.y - popupHeight - offsetY}px`,
      left: `${point.x - popupWidth / 2}px`,
    }
  } else {
    popupStyle.value = {
      top: `${point.y}px`,
      left: `${point.x}px`,
    }
  }
}
</script>

<style scoped>
.custom-popup {
  position: absolute;
  background: white;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.popup-content {
  text-align: left;
}
.btn {
  display: flex;
  justify-content: center;
}

button {
  margin-top: 10px;
  padding: 5px 10px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background: #0056b3;
}
</style>
